package com.mt.mtbusinessmanagementsystem.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mt.mtbusinessmanagementsystem.constant.*;
import com.mt.mtbusinessmanagementsystem.mapper.GeneralMapper;
import com.mt.mtbusinessmanagementsystem.pojo.dto.*;
import com.mt.mtbusinessmanagementsystem.pojo.entity.*;
import com.mt.mtbusinessmanagementsystem.pojo.properties.JWTProperties;
import com.mt.mtbusinessmanagementsystem.pojo.view.ProductsClassificationType;
import com.mt.mtbusinessmanagementsystem.service.GeneralService;
import com.mt.mtbusinessmanagementsystem.utils.IsTrue;
import com.mt.mtbusinessmanagementsystem.utils.JwtUtils;
import com.mt.mtbusinessmanagementsystem.utils.Result;
import com.mt.mtbusinessmanagementsystem.utils.entry.Entry;
import com.mt.mtbusinessmanagementsystem.utils.oss.OSSUtil;
import com.mt.mtbusinessmanagementsystem.utils.product.level.*;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class GeneralServiceImpl implements GeneralService {
    @Autowired
    private GeneralMapper generalMapper;
    @Autowired
    private JWTProperties jwtProperties;

    /**
     * 登录服务类，用于处理员工的登录请求。
     *
     * @param employee
     * @return
     */
    @Override
    public IsTrue<LoginDTO> login(Employee employee) {
        IsTrue<LoginDTO> isTrue = new IsTrue<>(true);
        //1.先获取工号对应的员工信息
        LoginDTO loginDTO = generalMapper.login(employee);
        //2.判断员工账号和密码是否对应,不符合则直接返回错误信息
        if (loginDTO == null) {
            isTrue.setIsTrue(false);
            return isTrue;
        }
        //3.更新最后的登录时间
        generalMapper.updateEmployeeInfo(Employee.builder().employeeId(loginDTO.getEmployeeId()).lastLoginTime(LocalDateTime.now()).build());
        //generalMapper.updateEmployeeLastDateTime(loginDTO.getEmployeeId(), LocalDateTime.now());
        //4.创建对应的token
        Map<String, Object> client = new HashMap<>();
        client.put(JWTConstant.EMPLOYEE_ID, loginDTO.getEmployeeId());
        client.put(JWTConstant.ACCOUNT, loginDTO.getAccount());
        client.put(JWTConstant.PASSWORD, loginDTO.getPassword());
        String token = JwtUtils.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), client, jwtProperties.getIssUer());
        //5.返回对应的数据
        loginDTO.setToken(token);
        isTrue.setData(loginDTO);
        return isTrue;
    }

    /**
     * 添加部门方法，添加部门同时,要添加一个员工作为部门主管。
     *
     * @param dept
     * @return
     */
    @Override
    public IsTrue<String> addDept(Dept dept) {
        IsTrue<String> isTrue = IsTrue.<String>builder().isTrue(true).build();
        //1.首先判断有没有这个部门名
        Integer count = generalMapper.isExistDept(dept);
        //1.1 如果有该部门名,直接返回错误信息
        if (count.equals(GeneralConstant.EXIST_NUMBER)) {
            isTrue.setIsTrue(false);
            isTrue.setStr(MessageConstant.DEPT_EXIST_ERROR);
            return isTrue;
        }
        //2.向部门表插入一条数据
        generalMapper.insertDept(dept);
        Integer postID = getPostID(PostConstant.SUPERVISOR_EMPLOYEES);
        //3.修改该名员工为主管
        if (dept.getEmployeeId() != null) {
            Employee employee = Employee.builder().employeeId(dept.getEmployeeId()).postsId(postID).deptId(getDeptID(dept.getDeptName())).build();
            generalMapper.updateEmployeeInfo(employee);
        }
        return isTrue;
    }

    /**
     * 删除部门方法，删除部门后,将部门主管的职位恢复成普通员工。
     * 删除前将该部门员工的所属部门改为未分配部门.
     *
     * @param deptId
     * @return
     */
    @Override
    public IsTrue<String> delDept(Integer deptId) {
        // 1. 部门表: 判断该部门是否存在
        Dept dept = generalMapper.getDeptById(deptId); // 此行更改
        if (dept == null) {
            return new IsTrue<>(false, "请注意: " + deptId + " 部门不存在, 你不能删除一个已经不存在的部门");
        }

        // 2. 员工表: 将部门的部门主管职位恢复成普通员工
        String employeeId = dept.getEmployeeId();
        if (employeeId != null) {
            generalMapper.updatePostToNormal(employeeId); // 此行更改
        }

        // 3. 员工表: 将隶属于该部门的员工的所属部门改为未分配部门 (ID = 9)
        generalMapper.updateDeptToUnassigned(deptId); // 此行更改

        // 4. 部门表: 删除该部门
        generalMapper.delDept(deptId); // 保持不变

        return new IsTrue<>(true, "部门删除成功");
    }


    /**
     * 修改部门方法,输入部门名和主管姓名,更换部门主管.
     *
     * @param deptDTO
     * @return
     */
    @Override
    public IsTrue<String> updateDept(DeptDTO deptDTO) {
        // 1. 先获取部门信息，确认部门是否存在
        Dept oldDeptInfo = getDept(deptDTO.getDeptName());
        if (oldDeptInfo == null) {
            return IsTrue.<String>builder().isTrue(false).str("部门不存在").build();
        }

        // 2. 获取新主管的员工ID
        String newManagerId = getEmployeeIdByName(deptDTO.getEmployeeName());
        if (newManagerId == null) {
            return IsTrue.<String>builder().isTrue(false).str("员工 " + deptDTO.getEmployeeName() + " 不存在").build();
        }

        // 3. 更新部门主管信息（修正：更新 `dept` 表的 `employee_id` 字段）
        deptDTO.setEmployeeId(newManagerId);
        generalMapper.updateDeptInfo(deptDTO);
        generalMapper.updateDeptManager(deptDTO.getDeptName(), newManagerId); // 额外更新 `dept.employee_id`

        // 4. 如果原来的主管存在，修改他的职位为普通员工（posts_id = 3）
        if (oldDeptInfo.getEmployeeId() != null) {
            generalMapper.updateEmployeeInfo(
                    Employee.builder()
                            .employeeId(oldDeptInfo.getEmployeeId())
                            .deptId(oldDeptInfo.getDeptId())
                            .postsId(3) // 旧主管降为普通员工
                            .build()
            );
        }

        // 5. 更新新主管的职位为部门主管（posts_id = 2）
        generalMapper.updateEmployeeInfo(
                Employee.builder()
                        .employeeId(newManagerId)
                        .deptId(oldDeptInfo.getDeptId())
                        .postsId(2) // 新主管职位设为部门主管
                        .build()
        );

        // 6. 返回成功信息
        return IsTrue.<String>builder().isTrue(true).str("成功：" + oldDeptInfo.getDeptName() + " 部门主管已修改为 " + deptDTO.getEmployeeName()).build();
    }

    /**
     * 获取员工姓名方法,根据员工的ID获取员工的姓名.
     *
     * @param employeeName
     * @return
     */
    @Override
    public String getEmployeeIdByName(String employeeName) {
        return generalMapper.getEmployeeIdByName(employeeName);
    }

    /**
     * 查询部门列表
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<DeptDTO> deptInfoByList(Integer pageNumber, Integer pageSize) {
        //1.根据接收到的信息进行分页
        PageHelper.startPage(pageNumber.intValue(), pageSize.intValue());
        ArrayList<DeptDTO> list = generalMapper.deptInfoByList();
        DeptDTO deptDTO = generalMapper.countDeptInfo();
        deptDTO.setDeptName(GeneralConstant.COMPANY);
        list.add(0, deptDTO);
        //2.返回数据
        return new PageInfo<>(list);
    }

    /**
     * 根据部门ID查询员工列表。
     *
     * @param deptId
     * @return
     */
    @Override
    public ArrayList<Employee> employeeByDept(Integer deptId) {
        return generalMapper.employeeByDept(deptId);
    }

    /**
     * 添加员工方法,员工工号格式固定:emp+数字(根据ID自增)
     *
     * @param employeeDTO
     * @return
     */
    @Override
    public IsTrue<String> addEmployee(EmployeeDTO employeeDTO) {
        // 1. 首先查询职位, 职位存在则返回职位号，不存在则添加职位，并重新查询
        Integer postID = getPostID(employeeDTO.getPostsName());
        if (postID == null) {
            generalMapper.insertPost(employeeDTO.getPostsName());
            postID = getPostID(employeeDTO.getPostsName());
        }
        employeeDTO.setPostsId(postID);

        // 2. 查询部门ID
        Integer deptID = getDeptID(employeeDTO.getDeptName());
        if (deptID == null) {
            // 如果部门不存在，可以选择添加部门或返回错误
            return IsTrue.<String>builder().isTrue(false).str(MessageConstant.DEPT_NOT_FOUND).build();
        }
        employeeDTO.setDeptId(deptID);

        // 3. 生成员工工号
//        String lastEmployeeId = generalMapper.getLastEmployeeId();
//        String newEmployeeId = lastEmployeeId + 1;
        String lastEmployeeId = generalMapper.getLastEmployeeId();// 获取当前最大id
        int nextId = 1;
        if (lastEmployeeId != null) {
            // 提取数字部分并生成下一个ID
            nextId = Integer.parseInt(lastEmployeeId.replace("emp", "")) + 1;
        }
        String newEmployeeId = String.format("emp%d", nextId); // 新的员工工号

        // 设置新生成的员工工号
        employeeDTO.setEmployeeId(newEmployeeId);

        // 4. 向员工表插入一条数据
        generalMapper.addEmployee(employeeDTO);

        // 5. 返回结果
        return IsTrue.<String>builder().isTrue(true).build();
    }

    //TODO 这里做account账号查重

    /**
     * 修改员工信息方法
     *
     * @param employeeDTO
     * @return
     */
    @Override
    public IsTrue<String> putEmployee(EmployeeDTO employeeDTO) {
        // 1. 根据员工工号查找员工
        EmployeeDTO existingEmployee = generalMapper.getEmployeeDTOById(employeeDTO.getEmployeeId());
        if (existingEmployee == null) {
            return IsTrue.<String>builder().isTrue(false).str(MessageConstant.EMPLOYEE_NOT_EXIST_ERROR).build();
        }

        // 2. 查询部门ID
        Integer deptID = getDeptID(employeeDTO.getDeptName());
        if (deptID == null) {
            return IsTrue.<String>builder().isTrue(false).str(MessageConstant.DEPT_NOT_FOUND).build();
        }
        employeeDTO.setDeptId(deptID);

        // 3. 查询职位ID
        Integer postID = getPostID(employeeDTO.getPostsName());
        if (postID == null) {
            return IsTrue.<String>builder().isTrue(false).str(MessageConstant.POST_NOT_FOUND).build();
        }
        employeeDTO.setPostsId(postID);

        // 4. 更新员工信息
        generalMapper.updateEmployeeInfo(employeeDTO);

        // 5. 返回成功
        return IsTrue.<String>builder().isTrue(true).build();
    }


    /**
     * 修改员工头像方法
     *
     * @param employeeId
     * @param headFile
     * @return
     */
    @Override
    public String putEmployeeHead(String employeeId, MultipartFile headFile) {
        //1.首先先上传头像并返回头像的url地址
        String url = OSSUtil.uploadFled(headFile, OSSConstant.EMPLOYEE_HEAD_DIRECTORY).getValue();
        //2.根据返回的url地址修改员工信息
        generalMapper.updateEmployeeInfo(Employee.builder().employeeId(employeeId).imageUrl(url).build());
        //3.返回数据
        return url;
    }

    /**
     * 删除员工方法,根据工号删除
     *
     * @param employeeDTO
     * @return
     */
    @Override
    public IsTrue<String> deleteEmployee(EmployeeDTO employeeDTO) {
        // 1. 根据员工工号查询员工
        EmployeeDTO existingEmployee = generalMapper.getEmployeeDTOById(employeeDTO.getEmployeeId());
        if (existingEmployee == null) {
            return IsTrue.<String>builder().isTrue(false).str(MessageConstant.EMPLOYEE_NOT_EXIST_ERROR).build();
        }

        // 2. 删除员工
        generalMapper.deleteEmployee(employeeDTO.getEmployeeId());

        // 3. 返回成功
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 查询员工列表方法
     *
     * @param employeeDTO
     * @return
     */
    @Override
    public List<EmployeeDTO> queryEmployee(EmployeeDTO employeeDTO) {
        return generalMapper.queryEmployeeList(employeeDTO);
    }
    //TODO 上下两个方法的区别和精简

    /**
     * 查询员工列表方法,分页查询
     *
     * @param employeeDTO
     * @return
     */
    @Override
    public PageInfo<EmployeeDTO> queryEmployeeList(EmployeeDTO employeeDTO) {
        //1. 判断传输过来的是否是部门名，是的话则重置为部门ID

        if (employeeDTO != null && employeeDTO.getPostsName() != null) {
            employeeDTO.setPostsId(getPostID(employeeDTO.getPostsName()));
        }
        ArrayList<EmployeeDTO> list;
        //2.分页查询员工列表
        if (employeeDTO != null && employeeDTO.getPageNumber() != null && employeeDTO.getPageSize() != null) {
            PageHelper.startPage(employeeDTO.getPageNumber().intValue(), employeeDTO.getPageSize().intValue());
            list = generalMapper.queryEmployeeList(employeeDTO);
        } else {
            list = generalMapper.queryEmployeeList(employeeDTO);
        }
        //3.返回数据
        return new PageInfo<>(list);
    }

    /**
     * 添加客户方法
     *
     * @param customerDTO
     * @return
     */
    @Override
    @Transactional
    public IsTrue<CustomerDTO> addCustomer(CustomerDTO customerDTO) {
        //0. 判断customerID是否为空,为空返回错误信息，不为空则进行下一步
        if (customerDTO.getCustomerId() == null) {
            return IsTrue.<CustomerDTO>builder().isTrue(false).str(String.format(MessageConstant.DATA_IS_NULL, GeneralConstant.CUSTOMER_ID)).build();
        }

        try {
            //1. 先查看是否有传输公司名,有的话查询是否有该家公司,没有的话进行下一步
            //1.1有的话直接返回公司号ID
            if (customerDTO.getCompanyName() != null) {
                Company company = getCompany(customerDTO.getCompanyName());
                //1.2没有的话直接插入一条数据，再查询公司号ID
                if (company == null) {
                    generalMapper.addCompany(customerDTO);
                    company = getCompany(customerDTO.getCompanyName());
                }
                customerDTO.setCompanyId(company.getCompanyId());
            }
            //2. 向客户表插入一条数据
            //2.1更新部分数据
            customerDTO.setCreateDate(LocalDateTime.now());
            customerDTO.setUpdateDate(LocalDateTime.now());
            //2.2向客户表插入数据
            generalMapper.addCustomer(customerDTO);
            //3.向跟进表插入一条数据
            generalMapper.addFollow(Follow.builder().customerId(customerDTO.getCustomerId())
                    .employeeId(customerDTO.getEmployeeId()).startDate(LocalDateTime.now()).build());
            //4. 返回一条数据
            return IsTrue.<CustomerDTO>builder().isTrue(true).data(customerDTO).build();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return IsTrue.<CustomerDTO>builder().isTrue(false).str(MessageConstant.CUSTOMER_ADD_ERROR).build();
        }
    }

    /**
     * 客户信息分页方法
     *
     * @param customerDTO
     * @return
     */
    @Override
    public PageInfo<CustomerDTO> queryCustomerList(CustomerDTO customerDTO) {
        //1. 先做分页设置
        PageHelper.startPage(customerDTO.getPageNumber().intValue(), customerDTO.getPageSize().intValue());
        //2. 再根据传递过来的信息进行查询
        ArrayList<CustomerDTO> list = generalMapper.queryCustomerList(customerDTO);
        for (CustomerDTO dto : list) {
            //2.1如果CompanyId为空就跳过,否则查询数据
            if (dto.getCompanyId() != null) {
                continue;
            }
            Company company = getCompany(dto.getCompanyId());
            dto.setCompanyName(company.getCompanyName());
            dto.setCompanyPeopleNumber(company.getCompanyPeopleNumber());
        }
        //3.返回数据
        return new PageInfo<>(list);
    }

    //TODO 用途

    /**
     * 查询并返回创建人和负责人相关的客户信息。
     *
     * @return
     */
    @Override
    public Entry<Entry<String, ArrayList<CustomerDTO>>, Entry<String, ArrayList<CustomerDTO>>> queryCreateAndResponsibleInfo() {
        //1. 查询创建人信息
        ArrayList<CustomerDTO> createInfo = generalMapper.queryCreateInfo();
        //2. 查询负责人信息
        ArrayList<CustomerDTO> responsibleInfo = generalMapper.queryResponsibleInfo();
        //3. 填入数据
        Entry<Entry<String, ArrayList<CustomerDTO>>, Entry<String, ArrayList<CustomerDTO>>> entry = new Entry<>(
                new Entry<>(GeneralConstant.CREATE_INFO, createInfo), new Entry<>(GeneralConstant.RESPONSIBLE_INFO, responsibleInfo));
        //4.返回数据
        return entry;
    }

    /**
     * 根据部门名查询员工列表
     *
     * @param deptName
     * @return
     */
    @Override
    public ArrayList<Employee> employeeByDeptName(String deptName) {
        //1. 根据部门名查询deptID
        Integer deptId = getDeptID(deptName);
        //2. 根据deptID返回员工列表并返回数据
        return generalMapper.employeeByDept(deptId);
    }

    /**
     * 更新客户信息，并更新跟进记录。
     *
     * @param customer
     */
    @Override
    @Transactional
    public void customerPut(Customer customer) {
        //1.更新时间并修改数据
        customer.setUpdateDate(LocalDateTime.now());
        generalMapper.customerPut(customer);
        //2.如果employeeID存在, 则意味着需要修改跟进表
        if (customer.getEmployeeId() != null) {
            Follow follow = getFollow(Follow.builder().customerId(customer.getCustomerId()).build());
            follow.setEmployeeId(customer.getEmployeeId());
            generalMapper.followPut(follow);
        }
    }

    /**
     * 获取客户的详细信息
     *
     * @param customerDTO
     * @return
     */
    @Override
    public IsTrue<CustomerDTO> customerDetailedInfo(CustomerDTO customerDTO) {
        //0. 查询是否传递customerId,没有则传递错误信息
        if (customerDTO.getCustomerId() == null) {
            return IsTrue.<CustomerDTO>builder().isTrue(false).str(String.format(MessageConstant.DATA_IS_NULL, GeneralConstant.CREATE_INFO)).build();
        }
        //1. 根据customerId先获取部分信息
        CustomerDTO newCustomer = generalMapper.customerDetailedInfo(customerDTO);
        //2. 再根据employeeId获取employeeName获取信息
        String employeeName = getEmployee(Employee.builder().employeeId(newCustomer.getEmployeeId()).build()).getEmployeeName();
        newCustomer.setEmployeeName(employeeName);
        //3. 返回数据
        return IsTrue.<CustomerDTO>builder().isTrue(true).data(newCustomer).build();
    }

    /**
     * 增加跟进方法
     *
     * @param followMethod
     * @return
     */
    @Override
    public IsTrue addFollowMethod(FollowMethod followMethod) {
        //1.先到数据库中查询是否有重复的信息,
        FollowMethod newFollowMethod = getFollowMethod(followMethod);
        //2.有重复信息则直接返回错误信息
        if (newFollowMethod != null) {
            return IsTrue.builder().isTrue(false).str(String.format(MessageConstant.DATA_EXIST_ERROR, GeneralConstant.FOLLOW_METHOD)).build();
        }
        //3.没有重复信息就直接向跟进方式表插入一条数据
        generalMapper.addFollowMethod(followMethod);
        //4.返回数据
        return IsTrue.builder().isTrue(true).build();
    }

    /**
     * 删除跟进方法
     *
     * @param followMethodId
     * @return
     */
    @Override
    @Transactional
    public IsTrue<String> delFollowMethod(Integer followMethodId) {
        //1. 首先先查询followMethodId是否存在
        FollowMethod followMethod = getFollowMethod(FollowMethod.builder().followMethodsId(followMethodId).build());
        //2. 不存在则代表不能删除,直接返回错误信息
        if (followMethod == null) {
            return IsTrue.<String>builder().isTrue(false).str(String.format(MessageConstant.DATA_NOT_EXIST_ERROR, GeneralConstant.FOLLOW_METHOD_ID)).build();
        }
        //3. 存在则直接删除信息
        generalMapper.delFollowMethod(followMethodId);
        //4. 返回删除成功信息
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 更新跟进方法
     *
     * @param followMethod
     * @return
     */
    @Override
    public IsTrue<FollowMethod> updateFollowMethod(FollowMethod followMethod) {
        //0. 如果followMethod为空，则直接返回错误信息
        if (followMethod.getFollowMethodsId() == null) {
            return IsTrue.<FollowMethod>builder().isTrue(false).str(String.format(MessageConstant.DATA_IS_NULL, GeneralConstant.FOLLOW_METHOD_ID)).build();
        }
        //1. 直接修改数据, 且要查询返回值
        Integer number = generalMapper.updateFollowMethod(followMethod);
        //2. 如果返回值为0, 则代表没有该数据, 就不需要修改, 直接返回错误信息
        if (number.equals(GeneralConstant.IS_EMPTY)) {
            return IsTrue.<FollowMethod>builder().isTrue(false).str(String.format(MessageConstant.DATA_NOT_EXIST_ERROR, GeneralConstant.FOLLOW_METHOD_ID)).build();
        }
        //3. 返回数据
        FollowMethod newFollowMethod = getFollowMethod(FollowMethod.builder().followMethodsId(followMethod.getFollowMethodsId()).build());
        return IsTrue.<FollowMethod>builder().isTrue(true).data(newFollowMethod).build();
    }

    /**
     * 查询跟进方法
     *
     * @return
     */
    @Override
    public ArrayList<FollowMethod> queryFollowMethod() {
        //1.直接查询跟进方式表
        ArrayList<FollowMethod> list = generalMapper.queryFollowMethod();
        //2.直接返回数据
        return list;
    }

    /**
     * 添加客户跟进进展记录
     *
     * @param followMethodsId
     * @param dateTime
     * @param progressInfo
     * @param fileList
     * @param employeeId
     * @param customerId
     * @return
     */
    @Transactional
    @Override
    public IsTrue<String> addProgress(Integer followMethodsId, LocalDateTime dateTime, String progressInfo, MultipartFile[] fileList, String employeeId, String customerId) {
        //1. 首先根据followMethodsId和customerId确定一个跟进表ID
        Follow follow = getFollow(Follow.builder().customerId(customerId).employeeId(employeeId).build());
        StringJoiner sj = null;
        //2. 进行文件上传
        if (fileList != null || fileList.length != 0) {
            sj = new StringJoiner("-");
            ArrayList<Entry<String, String>> newFileList = OSSUtil.uploadFledList(fileList, OSSConstant.FOLLOW_PROGRESS_DIRECTORY);
            //3. 根据返回的url地址, 向文件表插入数据
            //3.1为了方便扩展性, 转化为ArrayList<FileInfo>
            ArrayList<FileInfo> infoArrayList = new ArrayList<>(newFileList.size());
            for (Entry<String, String> entry : newFileList) {
                infoArrayList.add(new FileInfo(null, entry.getKey(), entry.getValue()));

            }
            //3.2向文件表插入一条数据,获取文件表ID
            generalMapper.addFile(infoArrayList);
            //4.根据infoArrayList去查询文件表数据
            ArrayList<FileInfo> fileInfoList = generalMapper.queryFileIdList(infoArrayList);
            //5. 根据文件表ID,向一定的规律排序, 就比如: 1-2-3
            for (FileInfo fileInfo : fileInfoList) {
                sj.add(fileInfo.getFileId().toString());
            }

        }
        Progress progress = Progress.builder().followMethodsId(followMethodsId).progressInfo(progressInfo).date(dateTime)
                .fileArrayId(sj.toString()).followId(follow.getFollowId()).employeeId(employeeId).build();
        //6. 向进展表插入一条数据
        generalMapper.addProgress(progress);
        //7. 返回上传成功的数据
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 查询客户跟进进展列表
     *
     * @param customerDTO
     * @return
     */
    @Transactional
    @Override
    public IsTrue<ArrayList<ProgressDTO>> queryProgressList(CustomerDTO customerDTO) {
        if (customerDTO.getCustomerId() == null) {
            return IsTrue.<ArrayList<ProgressDTO>>builder().isTrue(false)
                    .str(String.format(MessageConstant.DATA_NOT_EXIST_ERROR, GeneralConstant.CUSTOMER_ID)).build();
        }
        //0. 分页
        PageHelper.startPage(customerDTO.getPageNumber().intValue(), customerDTO.getPageSize().intValue());
        //1. 首先根据客户ID获取跟进表ID
        ArrayList<ProgressDTO> list = generalMapper.queryProgressList(customerDTO);
        //2. 根据进展表数据获取文件的url
        for (ProgressDTO progressDTO : list) {
            if (progressDTO.getFileArrayId() == null) {
                continue;
            }

            String[] split = progressDTO.getFileArrayId().split(GeneralConstant.FILE_URL_REGEX);
            if (split.length == 0) {
                continue;
            }
            progressDTO.setFileInfoList(getFileArrayList(split));
        }
        //3. 返回数据
        return IsTrue.<ArrayList<ProgressDTO>>builder().isTrue(true).data(list).build();
    }

    /**
     * 产品分类方法
     *
     * @param productsClassificationDTO
     * @return
     */
    @Override
    public IsTrue<String> addProductClass(ProductsClassificationDTO productsClassificationDTO) {
        //1. 判断一级分类是否存在，存在则直接获取一级分类ID，不存在则直接获取一级分类最大ID+1
        ProductsClassificationDTO result = ProductsClassificationDTO.builder()
                .firstClassificationName(productsClassificationDTO.getFirstClassificationName())
                .secondClassificationName(productsClassificationDTO.getSecondClassificationName())
                .thirdClassificationName(productsClassificationDTO.getThirdClassificationName())
                .fourthLevelClassificationName(productsClassificationDTO.getFourthLevelClassificationName())
                .levelNumber(LevelConstant.FIRST_LEVEL)
                .employeeId(productsClassificationDTO.getEmployeeId())
                .build();
        setLevelNumber(result);
        //2. 判断二级分类是否存在，存在则直接获取二级分类ID，不存在则直接获取二级分类最大ID+1
        result.setLevelNumber(LevelConstant.SECOND_LEVEL);
        setLevelNumber(result);
        //3. 判断三级分类是否存在，存在则直接获取三级分类ID，不存在则直接获取三级分类最大ID+1
        result.setLevelNumber(LevelConstant.THIRD_LEVEL);
        setLevelNumber(result);
        //4. 判断四级分类是否存在，存在则直接获取四级分类ID，不存在则直接获取四级分类最大ID+1
        result.setLevelNumber(LevelConstant.FOURTH_LEVEL);
        setLevelNumber(result);
        //5. 如果四个分类都存在，则代表不需要增加分类，直接返回错误信息就行了
        if (result.getIsFirstExist() && result.getIsSecondExist() && result.getIsThirdExist() && result.getIsFourthExist()) {
            return IsTrue.<String>builder().isTrue(false).str(String.format(MessageConstant.DATA_EXIST_ERROR, GeneralConstant.EMPTY_STRING)).build();
        }
        //6. 插入数据
        result.setDate(LocalDateTime.now());
        generalMapper.addProductClass(result);
        //7. 返回数据
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 查询文件的地址
     *
     * @param fileInfo
     * @return
     */
    @Override
    public IsTrue<FileInfo> searchFileUrl(FileInfo fileInfo) {
        //1. 查询文件的url
        FileInfo fileInfo1 = getFileInfo(fileInfo);
        //2. 返回数据
        return IsTrue.<FileInfo>builder().isTrue(true).data(fileInfo1).build();
    }

    /**
     * 查询产品分类信息
     *
     * @return
     */
    @Override
    public IsTrue<ArrayList<FirstLevel>> searchProductsClassificationType() {
        //1. 查询产品分类信息
        ArrayList<FirstLevel> list = getLevelList();
        //2. 返回数据
        return IsTrue.<ArrayList<FirstLevel>>builder().isTrue(true).data(list).build();
    }

    /**
     * 修改产品分类
     *
     * @param productsClassificationType
     * @return
     */
    @Transactional
    @Override
    public IsTrue<String> putProductsClassification(ProductsClassificationType productsClassificationType) {
        //1. 先获取数据
        String productsClassificationId = productsClassificationType.getProductsClassificationId();
        String productsClassificationTypeName = productsClassificationType.getProductsClassificationTypeName();
        //2. 对数据进行切片
        String[] split = productsClassificationId.split(GeneralConstant.FILE_URL_REGEX);
        String[] split1 = productsClassificationTypeName.split(GeneralConstant.FILE_URL_REGEX);
        //3. 装填数据
        ProductsClassification productsClassification = ProductsClassification.builder()
                .firstClassificationId(Integer.parseInt(split[0]))
                .secondClassificationId(Integer.parseInt(split[1]))
                .thirdClassificationId(Integer.parseInt(split[2]))
                .fourLevelClassificationId(Integer.parseInt(split[3]))
                .firstClassificationName(split1[0])
                .secondClassificationName(split1[1])
                .thirdClassificationName(split1[2])
                .fourLevelClassificationName(split1[3])
                .build();
        //4. 根据数据进行修改产品分类表数据
        try {
            generalMapper.putProductsClassification(productsClassification);
        } catch (RuntimeException exception) {
            //4.1 编辑错误信息，并日志记录错误信息，再返回数据
            String msg = String.format(MessageConstant.DATA_ILLEGAL, GeneralConstant.PRODUCTS_CLASSIFICATION_TYPE);
            log.error(msg);
            return IsTrue.<String>builder().isTrue(false).str(msg).build();
        }
        //5. 返回数据
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 删除产品分类
     *
     * @param productsClassificationType
     * @return
     */
    @Override
    public IsTrue<String> delProductsClassification(ProductsClassificationType productsClassificationType) {
        //1. 先获取数据
        String productsClassificationTypeId = productsClassificationType.getProductsClassificationTypeId();
        //2. 对数据进行切片
        List<Integer> list = Arrays.stream(productsClassificationTypeId.split(GeneralConstant.FILE_URL_REGEX)).map(Integer::parseInt).toList();
        //3. 装填数据
        ProductsClassification productsClassification = ProductsClassification.builder()
                .firstClassificationId(list.get(0))
                .secondClassificationId(list.get(1))
                .thirdClassificationId(list.get(2))
                .fourLevelClassificationId(list.get(3))
                .build();
        //4. 根据数据进行删除产品分类表数据
        try {
            Integer count = generalMapper.delProductsClassification(productsClassification);
            //4.1判断该数据是否存在，不存在则直接返回错误信息
            if (count.equals(GeneralConstant.IS_EMPTY)) {
                return IsTrue.<String>builder().isTrue(false)
                        .str(String.format(MessageConstant.DATA_NOT_EXIST_ERROR, productsClassificationTypeId)).build();
            }
        } catch (RuntimeException exception) {
            //4.2 编辑错误信息，并日志记录错误信息，再返回数据
            log.error(String.format(MessageConstant.DATA_NOT_EXIST_ERROR, productsClassificationTypeId));
            return IsTrue.<String>builder().isTrue(false)
                    .str(String.format(MessageConstant.DATA_ILLEGAL, GeneralConstant.PRODUCTS_CLASSIFICATION_TYPE)).build();
        }
        //5. 返回数据
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 增加产品方法
     *
     * @param productsDTO
     * @return
     */
    @Transactional
    @Override
    public IsTrue<String> addProduct(ProductsDTO productsDTO) {
        //1. 判断员工是否是业务部主管
        if (!isEmployeeOfDeptAndPosts(DeptConstant.BUSINESS, PostConstant.SUPERVISOR_EMPLOYEES, productsDTO.getEmployeeId())) {
            //1.1如果该名员工并不是主管，则会直接返回错误信息
            return IsTrue.<String>builder().isTrue(false)
                    .str(String.format(MessageConstant.NOT_POST_OF_EMPLOYEE, DeptConstant.BUSINESS + PostConstant.SUPERVISOR_EMPLOYEES)).build();
        }
        //2. 判断供应商是否存在, 存在则直接获取供应商ID, 不存在则创建一个供应商
        if (productsDTO.getVendorCompanyChineseName() != null || !productsDTO.getVendorCompanyChineseName().equals(GeneralConstant.EMPTY_STRING)
                || productsDTO.getProductsEnglishName() != null || !productsDTO.getProductsEnglishName().equals(GeneralConstant.EMPTY_STRING)) {
            VendorCompany vendorCompany = getOrCreateVendorCompany(VendorCompany.builder()
                    .vendorCompanyEnglishName(productsDTO.getVendorCompanyEnglishName())
                    .vendorCompanyChineseName(productsDTO.getVendorCompanyChineseName()).build());
            productsDTO.setVendorCompanyId(vendorCompany.getVendorCompanyId());
        }
        //3. 判断品牌是否存在, 存在则直接获取品牌ID, 不存在则创建一个品牌(目前不涉及品牌)
        //4. 判断文件是否存在, 存在则直接往文件表插入数据, 不存在则直接通过
        if (productsDTO.getFiles() != null && productsDTO.getFiles().length > 0) {
            String fileURL = uploadFileList(productsDTO.getFiles(), OSSConstant.PRODUCTS_DIRECTORY);
            productsDTO.setProductsImageArrayId(fileURL);
        }
        //5. 向产品表插入一条数据
        productsDTO.setDate(LocalDateTime.now());
        productsDTO.setUpdateTime(LocalDateTime.now());
        generalMapper.addProduct(productsDTO);
        //6. 返回数据
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 修改产品信息方法
     *
     * @param productsDTO
     * @return
     */
    @Override
    public IsTrue<String> putProduct(ProductsDTO productsDTO) {
        //1. 判断员工是否是业务部主管
        if (!isEmployeeOfDeptAndPosts(DeptConstant.BUSINESS, PostConstant.SUPERVISOR_EMPLOYEES, productsDTO.getEmployeeId())) {
            //1.1如果该名员工并不是主管，则会直接返回错误信息
            return IsTrue.<String>builder().isTrue(false)
                    .str(String.format(MessageConstant.NOT_POST_OF_EMPLOYEE, DeptConstant.BUSINESS + PostConstant.SUPERVISOR_EMPLOYEES)).build();
        }
        //2. 判断供应商是否存在, 存在则直接获取供应商ID, 不存在则创建一个供应商
        if (productsDTO.getVendorCompanyId() != null && (productsDTO.getVendorCompanyChineseName() != null || !productsDTO.getVendorCompanyChineseName().equals(GeneralConstant.EMPTY_STRING)
                || productsDTO.getProductsEnglishName() != null || !productsDTO.getProductsEnglishName().equals(GeneralConstant.EMPTY_STRING))) {
            VendorCompany vendorCompany = VendorCompany.builder()
                    .vendorCompanyEnglishName(productsDTO.getVendorCompanyEnglishName())
                    .vendorCompanyChineseName(productsDTO.getVendorCompanyChineseName())
                    .vendorCompanyId(productsDTO.getVendorCompanyId())
                    .build();
            generalMapper.putVendorCompany(vendorCompany);
            vendorCompany = getVendorCompany(vendorCompany);
            productsDTO.setVendorCompanyId(vendorCompany.getVendorCompanyId());
        }
        //3. 假如文件存在,则需要重新穿上图片，并修改相应的产品图片数据
        if (productsDTO.getFiles() != null) {
            String fileURL = uploadFileList(productsDTO.getFiles(), OSSConstant.PRODUCTS_DIRECTORY);
            productsDTO.setProductsImageArrayId(fileURL);
        }
        productsDTO.setUpdateTime(LocalDateTime.now());
        //4. 修改文件表信息
        generalMapper.putProduct(productsDTO);
        //5. 返回修改成功信息
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 删除产品方法
     *
     * @param productsDTO
     * @return
     */
    @Override
    public IsTrue<String> delProduct(ProductsDTO productsDTO) {
        //1. 判断员工是否是业务部主管
        if (!isEmployeeOfDeptAndPosts(DeptConstant.BUSINESS, PostConstant.SUPERVISOR_EMPLOYEES, productsDTO.getEmployeeId())) {
            //1.1如果该名员工并不是主管，则会直接返回错误信息
            return IsTrue.<String>builder().isTrue(false)
                    .str(String.format(MessageConstant.NOT_POST_OF_EMPLOYEE, DeptConstant.BUSINESS + PostConstant.SUPERVISOR_EMPLOYEES)).build();
        }
        //2. 开始删除数据
        try {
            Integer count = generalMapper.delProduct(Products.builder().id(productsDTO.getId()).build());
            //2.1删除结果为0，返回错误信息
            if (count.equals(GeneralConstant.IS_EMPTY)) {
                return IsTrue.<String>builder().isTrue(false).str(String.format(MessageConstant.DATA_ILLEGAL, productsDTO.getId())).build();
            }
        } catch (RuntimeException exception) {
            //2.2删除结果报错，返回错误信息
            return IsTrue.<String>builder().isTrue(false).str(String.format(MessageConstant.DATA_ILLEGAL, productsDTO.getId())).build();
        }
        //3. 返回删除成功的结果
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 查询产品方法
     *
     * @param productsDTO
     * @return
     */
    @Override
    public IsTrue<PageInfo<ProductsDTO>> queryProduct(ProductsDTO productsDTO) {
        //1. 进行分页
        PageHelper.startPage(productsDTO.getPageNumber().intValue(), productsDTO.getPageSize().intValue());
        //2. 查询数据
        ArrayList<ProductsDTO> list = generalMapper.queryProduct(productsDTO);
        //3. 遍历查询文件数据
        for (ProductsDTO productsDTO1 : list) {
            if (productsDTO1.getProductsImageArrayId() == null) {
                continue;
            }
            String[] fileList = productsDTO1.getProductsImageArrayId().split(GeneralConstant.FILE_URL_REGEX);
            ArrayList<FileInfo> fileArrayList = getFileArrayList(fileList);
            productsDTO1.setFileList(fileArrayList);
        }
        //4. 返回结果
        return IsTrue.<PageInfo<ProductsDTO>>builder().isTrue(true).data(new PageInfo<>(list)).build();
    }

    /**
     * 增加产品数量方法
     *
     * @param productsDTO
     * @return
     */
    @Transactional
    @Override
    public IsTrue<Products> addProductNumber(ProductsDTO productsDTO) {
        if (productsDTO.getEmployeeId() == null || productsDTO.getEmployeeId().equals(GeneralConstant.EMPTY_STRING)) {
            return IsTrue.<Products>builder().isTrue(false)
                    .str(String.format(MessageConstant.DATA_ADD_FAILED, GeneralConstant.EMPLOYEE_ID)).build();
        }
        //1. 根据ID添加产品数量
        productsDTO.setUpdateTime(LocalDateTime.now());
        productsDTO.setInOrOutStorage(GeneralConstant.IN_STORAGE);
        Integer count = generalMapper.updateProductNumber(productsDTO);
        if (count.equals(GeneralConstant.IS_EMPTY)) {
            return IsTrue.<Products>builder().isTrue(false)
                    .str(String.format(MessageConstant.DATA_ADD_FAILED, GeneralConstant.PRODUCTS_NUMBER)).build();
        }
        //2. 查询数据
        Products newProducts = getProduct(Products.builder().id(productsDTO.getId()).productsId(productsDTO.getProductsId()).build());
        //3. 记录在产品日志表上
        String str = String.format(MessageConstant.PRODUCT_ADD_LOG, productsDTO.getEmployeeId(), productsDTO.getProductsId(), productsDTO.getProductsNumber());
        ProductsLog productsLog = ProductsLog.builder().productsId(newProducts.getProductsId()).inOrOutStorage(GeneralConstant.IN_STORAGE)
                .log(str).employeeId(productsDTO.getEmployeeId()).productsNumber(productsDTO.getProductsNumber())
                .date(LocalDateTime.now()).vendorCompanyId(newProducts.getVendorCompanyId()).productsMoney(productsDTO.getProductsMoney()).build();
        //4. 届时可能需要修改
        generalMapper.addProductLog(productsLog);
        //5. 返回数据
        return IsTrue.<Products>builder().isTrue(true).data(newProducts).build();
    }

    /**
     * 删除产品数量方法
     *
     * @param productsDTO
     * @return
     */
    @Override
    public IsTrue<Products> decreaseProductNumber(ProductsDTO productsDTO) {
        if (productsDTO.getEmployeeId() == null || productsDTO.getEmployeeId().equals(GeneralConstant.EMPTY_STRING)) {
            return IsTrue.<Products>builder().isTrue(false)
                    .str(String.format(MessageConstant.DATA_ADD_FAILED, GeneralConstant.EMPLOYEE_ID)).build();
        }
        //1. 根据ID减少产品数量
        productsDTO.setUpdateTime(LocalDateTime.now());
        productsDTO.setInOrOutStorage(GeneralConstant.OUT_STORAGE);
        Products product = getProduct(Products.builder().productsId(productsDTO.getProductsId()).build());
        //1.1判断产品是否存在，存在则直接进行判断数量是否足够，不足够或者产品不存在则直接返回错误信息
        if (product == null) {
            return IsTrue.<Products>builder().isTrue(false)
                    .str(String.format(MessageConstant.DATA_NOT_EXIST_ERROR, productsDTO.getProductsId())).build();
        } else if (product.getProductsNumber() < productsDTO.getProductsNumber()) {
            return IsTrue.<Products>builder().isTrue(false).str(String.format(MessageConstant.DATA_NUMBER_NOT_ENOUGH, GeneralConstant.PRODUCTS_NUMBER)).build();
        }
        Integer count = generalMapper.updateProductNumber(productsDTO);
        if (count.equals(GeneralConstant.IS_EMPTY)) {
            return IsTrue.<Products>builder().isTrue(false)
                    .str(String.format(MessageConstant.DATA_ADD_FAILED, GeneralConstant.PRODUCTS_NUMBER)).build();
        }
        //2. 查询数据
        Products newProducts = getProduct(Products.builder().id(productsDTO.getId()).productsId(productsDTO.getProductsId()).build());
        //3. 记录在产品日志表上
        String str = String.format(MessageConstant.PRODUCT_DECREASE_LOG, productsDTO.getEmployeeId(), productsDTO.getProductsId(), productsDTO.getProductsNumber());
        ProductsLog productsLog = ProductsLog.builder().productsId(newProducts.getProductsId()).inOrOutStorage(GeneralConstant.OUT_STORAGE)
                .log(str).employeeId(productsDTO.getEmployeeId()).productsNumber(productsDTO.getProductsNumber())
                .date(LocalDateTime.now()).vendorCompanyId(newProducts.getVendorCompanyId()).productsMoney(productsDTO.getProductsMoney()).build();
        //4. 届时可能需要修改
        generalMapper.addProductLog(productsLog);
        //5. 返回数据
        return IsTrue.<Products>builder().isTrue(true).data(newProducts).build();
    }

    /**
     * 增加订单方法
     *
     * @param mtOrderDTO
     * @return
     */
    @Transactional
    @Override
    public IsTrue<String> addMtOrder(MTOrderDTO mtOrderDTO) {
        //1. 如果没有预期销售金额，只有单价和数量可以先计算出来
        if (mtOrderDTO.getSaleTotalMoneyPlan() == null) {
            mtOrderDTO.setSaleTotalMoneyPlan(mtOrderDTO.getUnitPrice() * mtOrderDTO.getProductsNumber());
        }
        //2. 根据优惠比例计算实际销售金额, 如果实际销售金额有上传, 则直接根据实际销售金额来
        if (mtOrderDTO.getSaleTotalMoneyActual() == null) {
            mtOrderDTO.setSaleTotalMoneyActual(mtOrderDTO.getSaleTotalMoneyPlan() * mtOrderDTO.getDiscountRatio());
        }
        //3. 如果未设置销售人员, 则直接根据上传的员工工号为销售人员
        if (mtOrderDTO.getSalesperson() == null) {
            mtOrderDTO.setSalesperson(mtOrderDTO.getEmployeeId());
            mtOrderDTO.setSalespersonApproval(OrderConstant.PASS);
        }
        //4. 设置初始状态
        mtOrderDTO.setState(OrderConstant.INIT_STATE);
        //5. 更新提交时间
        mtOrderDTO.setSubmitDate(LocalDateTime.now());
        //6. 插入一条数据
        try {
            synchronized (mtOrderDTO) {
                generalMapper.addMtOrder(mtOrderDTO);
            }
        } catch (RuntimeException runtimeException) {
            //6.1如果有错误信息直接返回错误信息
            String msg = String.format(MessageConstant.DATA_ADD_FAILED, GeneralConstant.EMPTY_STRING);
            log.error(msg);
            return IsTrue.<String>builder().isTrue(false).str(msg).build();
        }
        //7. 返回数据
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 修改订单信息方法
     *
     * @param mtOrderDTO
     * @return
     */
    @Override
    public IsTrue<MTOrderDTO> putMtOrder(MTOrderDTO mtOrderDTO) {
        //1. 判断id是否存在
        if (mtOrderDTO.getOrderId() == null) {
            return IsTrue.<MTOrderDTO>builder().isTrue(false)
                    .str(String.format(MessageConstant.DATA_NOT_EXIST_ERROR, GeneralConstant.ORDER_ID)).build();
        }
        //2. 修改数据
        try {
            synchronized (mtOrderDTO) {
                generalMapper.updateMtOrder(mtOrderDTO);
            }
        } catch (RuntimeException e) {
            //2.1发生异常则返回错误数据
            return IsTrue.<MTOrderDTO>builder().isTrue(false)
                    .str(String.format(MessageConstant.DATA_UPDATED_FAILED, GeneralConstant.ORDER_ID)).build();
        }
        //3. 根据id查询已经修改的数据
        MTOrderDTO newMTOrder = getMtOrder(mtOrderDTO);
        //4. 判断该订单是否被通过, 通过了再修改数据
        if (newMTOrder.getSalespersonApproval() != null && newMTOrder.getFinancialApproval() != null
                && newMTOrder.getManagerApproval() != null) {
            if (newMTOrder.getSalespersonApproval().equals(OrderConstant.PASS)
                    && newMTOrder.getFinancialApproval().equals(OrderConstant.PASS)
                    && newMTOrder.getManagerApproval().equals(OrderConstant.PASS)) {
                //4.1修改相应的数据
                synchronized (mtOrderDTO) {
                    generalMapper.updateMtOrder(MTOrderDTO.builder().orderId(mtOrderDTO.getOrderId())
                            .approvalDate(LocalDateTime.now()).state(OrderConstant.PASS_STATE).build());
                    newMTOrder = getMtOrder(MTOrderDTO.builder().orderId(mtOrderDTO.getOrderId()).build());
                }
                //4.2减少相应的数量
                decreaseProductNumber(ProductsDTO.builder().productsId(newMTOrder.getProductsId())
                        .productsNumber(newMTOrder.getProductsNumber()).employeeId(newMTOrder.getEmployeeId()).build());
            }
        }
        //5. 返回数据
        return IsTrue.<MTOrderDTO>builder().isTrue(true).data(newMTOrder).build();
    }

    /**
     * 查询订单列表方法
     *
     * @param mtOrderDTO
     * @return
     */
    @Override
    public IsTrue<PageInfo<MTOrderDTO>> queryMtOrderList(MTOrderDTO mtOrderDTO) {
        //1. 首先进行分页
        PageHelper.startPage(mtOrderDTO.getPageNumber().intValue(), mtOrderDTO.getPageSize().intValue());
        //2. 在进行查询
        ArrayList<MTOrderDTO> list = generalMapper.queryMtOrderList(mtOrderDTO);
        //3. 返回数据
        return IsTrue.<PageInfo<MTOrderDTO>>builder().isTrue(true).data(new PageInfo<>(list)).build();
    }

    /**
     * 增加买家卖家信息表方法
     *
     * @param sellerAndBuyerInfo
     * @return
     */
    @Transactional
    @Override
    public IsTrue<String> addSellerInfo(SellerAndBuyerInfo sellerAndBuyerInfo) {
        try {
            log.info("准备插入数据: {}", sellerAndBuyerInfo);
            generalMapper.addSellerInfo(sellerAndBuyerInfo);
            log.info("数据插入成功");
        } catch (RuntimeException exception) {
            log.error("插入数据失败: ", exception);
            return IsTrue.<String>builder()
                    .isTrue(false)
                    .str(String.format(MessageConstant.DATA_ADD_FAILED, GeneralConstant.EMPTY_STRING))
                    .build();
        }
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 删除买家卖家信息表方法
     *
     * @param sellerInfoId
     * @return
     */
    @Transactional
    @Override
    public IsTrue<String> deleteSellerInfo(Integer sellerInfoId) {
        try {
            log.info("准备删除ID为 {} 的数据", sellerInfoId);
            generalMapper.deleteSellerInfo(sellerInfoId);
            log.info("数据删除成功");
        } catch (RuntimeException exception) {
            log.error("删除数据失败: ", exception);
            return IsTrue.<String>builder()
                    .isTrue(false)
                    .str(String.format(MessageConstant.DATA_DELETE_FAILED, GeneralConstant.EMPTY_STRING))
                    .build();
        }
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 查询买家卖家信息表方法
     *
     * @param sellerAndBuyerInfo
     * @return
     */
    @Transactional
    @Override
    public IsTrue<List<SellerAndBuyerInfo>> querySellerInfoList(SellerAndBuyerInfo sellerAndBuyerInfo) {
        try {
            List<SellerAndBuyerInfo> sellerInfoList = generalMapper.querySellerInfoList(sellerAndBuyerInfo);
            if (sellerInfoList.isEmpty()) {
                return IsTrue.<List<SellerAndBuyerInfo>>builder().isTrue(false).str("没有找到相关数据").build();
            }
            return IsTrue.<List<SellerAndBuyerInfo>>builder().isTrue(true).data(sellerInfoList).build();
        } catch (Exception e) {
            log.error("查询卖家买家信息失败: ", e);
            return IsTrue.<List<SellerAndBuyerInfo>>builder().isTrue(false).str("查询失败").build();
        }
    }

    /**
     * 修改买家卖家信息表方法
     *
     * @param sellerAndBuyerInfo
     * @return
     */
    @Transactional
    @Override
    public IsTrue<String> updateSellerInfo(SellerAndBuyerInfo sellerAndBuyerInfo) {
        try {
            log.info("准备更新数据: {}", sellerAndBuyerInfo);
            generalMapper.updateSellerInfo(sellerAndBuyerInfo);
            log.info("数据更新成功");
        } catch (RuntimeException exception) {
            log.error("更新数据失败: ", exception);
            return IsTrue.<String>builder()
                    .isTrue(false)
                    .str(String.format(MessageConstant.DATA_UPDATED_FAILED, GeneralConstant.EMPTY_STRING))
                    .build();
        }
        return IsTrue.<String>builder().isTrue(true).build();
    }

    /**
     * 获取订单详情
     *
     * @param mtOrderDTO
     * @return
     */
    private MTOrderDTO getMtOrder(MTOrderDTO mtOrderDTO) {
        MTOrderDTO obj = generalMapper.getMtOrder(mtOrderDTO);
        return obj;
    }

    /**
     * 获取产品表
     *
     * @param products
     * @return
     */
    private Products getProduct(Products products) {
        Products newProducts = generalMapper.getProduct(products);
        return newProducts;
    }

    /**
     * 上传文件列表到指定的URL，并将文件信息保存到数据库
     *
     * @param files
     * @param url
     * @return
     */
    private String uploadFileList(MultipartFile[] files, String url) {
        StringJoiner sj = new StringJoiner(GeneralConstant.FILE_URL_REGEX);
        ArrayList<Entry<String, String>> newFileList = OSSUtil.uploadFledList(files, url);
        ArrayList<FileInfo> infoArrayList = new ArrayList<>(newFileList.size());
        for (Entry<String, String> entry : newFileList) {
            infoArrayList.add(new FileInfo(null, entry.getKey(), entry.getValue()));
        }
        generalMapper.addFile(infoArrayList);
        ArrayList<FileInfo> fileInfoList = generalMapper.queryFileIdList(infoArrayList);
        for (FileInfo fileInfo : fileInfoList) {
            sj.add(fileInfo.getFileId().toString());
        }
        return sj.toString();
    }

    //TODO 查重

    /**
     * 获取或创建供应商公司信息
     *
     * @param vendorCompany
     * @return
     */
    private VendorCompany getOrCreateVendorCompany(VendorCompany vendorCompany) {
        VendorCompany myVendorCompany = getVendorCompany(vendorCompany);
        if (myVendorCompany == null) {
            synchronized (myVendorCompany) {
                insertVendorCompany(vendorCompany);
                myVendorCompany = getVendorCompany(vendorCompany);
            }
        }
        return myVendorCompany;
    }

    /**
     * 插入供应商信息
     *
     * @param vendorCompany
     */
    private void insertVendorCompany(VendorCompany vendorCompany) {
        generalMapper.insertVendorCompany(vendorCompany);
    }

    /**
     * 获取供应商信息
     * @param vendorCompany
     * @return
     */
    private VendorCompany getVendorCompany(VendorCompany vendorCompany) {
        return vendorCompany == null ? null : generalMapper.getVendorCompany(vendorCompany);
    }
    //TODO 检查有无必要
    /**
     *判断一个员工是否属于特定的部门和职位
     * @param deptName
     * @param post
     * @param employeeId
     * @return
     */
    private boolean isEmployeeOfDeptAndPosts(String deptName, String post, String employeeId) {
        return isEmployeeOfDeptAndPosts(deptName, post, employeeId, false);
    }

    /**
     *判断一个员工是否属于特定的部门和职位
     * @param deptName
     * @param post
     * @param employeeId
     * @param isFuzzyQuery
     * @return
     */
    private boolean isEmployeeOfDeptAndPosts(String deptName, String post, String employeeId, boolean isFuzzyQuery) {
        //1. 获取员工信息
        Employee employee = getEmployee(Employee.builder().employeeId(employeeId).build());
        //2. 获取员工的部门
        Dept dept = getDept(Dept.builder().deptId(employee.getDeptId()).build());
        //3. 获取的员工的职位
        Posts posts = getPosts(Posts.builder().postsId(employee.getPostsId()).build());
        //4. 比较并返回数据
        return dept.getDeptName().contains(deptName) && post.equals(posts.getPostsName());
    }

    /**
     *根据职位获取职位详情
     * @param posts
     * @return
     */
    private Posts getPosts(Posts posts) {
        return generalMapper.getPosts(posts);
    }
//TODO 暂时不用
    /**
     *根据部门名称和员工ID模糊查询,暂时不用
     * @param deptName
     * @param employeeId
     * @return
     */
    private Dept getFuzzyDept(String deptName, String employeeId) {
        Dept dept = generalMapper.getFuzzyDept(deptName, employeeId);
        return dept;
    }

    /**
     * 获取产品分类的层级列表，包括一级到四级分类。
     *
     * 该方法首先获取一级分类列表，然后依次获取每个一级分类下的二级、三级和四级分类列表，
     * 并将它们组装成层级结构的数据。
     *
     * @return
     */
    private ArrayList<FirstLevel> getLevelList() {
        //1. 首先先获取一级分类，先获取必要的数据
        ArrayList<FirstLevel> list = getFirstList();
        //2. 再根据获取的一级分类获取二级分类
        for (FirstLevel firstLevel : list) {
            //2.1装填一级分类数据
            ProductsClassificationDTO productsClassificationDTO = ProductsClassificationDTO.builder().
                    firstClassificationId(firstLevel.getFirstClassificationId())
                    .firstClassificationName(firstLevel.getFirstClassificationName())
                    .levelNumber(LevelConstant.SECOND_LEVEL).build();
            //2.2查询二级分类并转换为List<SecondLevel>
            List<SecondLevel> secondList = generalMapper.getLevelList(productsClassificationDTO)
                    .stream().map(FatherLevel::fromSecondLevel).toList();
            //3. 再根据获取的数据获取三级分类
            for (SecondLevel secondLevel : secondList) {
                //3.1装填二级分类数据
                productsClassificationDTO.setSecondClassificationId(secondLevel.getSecondClassificationId());
                productsClassificationDTO.setSecondClassificationName(secondLevel.getSecondClassificationName());
                productsClassificationDTO.setLevelNumber(LevelConstant.THIRD_LEVEL);
                //3.2查询三级分类并转换为List<ThirdLevel>
                List<ThirdLevel> thirdLevelArrayList = generalMapper.getLevelList(productsClassificationDTO)
                        .stream().map(FatherLevel::fromThirdLevel).toList();
                //4. 再根据获取的数据获取四级分类
                for (ThirdLevel thirdLevel : thirdLevelArrayList) {
                    //4.1装填三级级分类数据
                    productsClassificationDTO.setThirdClassificationId(thirdLevel.getThirdClassificationId());
                    productsClassificationDTO.setThirdClassificationName(thirdLevel.getThirdClassificationName());
                    productsClassificationDTO.setLevelNumber(LevelConstant.FOURTH_LEVEL);
                    //4.2查询四级分类并转换为List<FourthLevel>
                    List<FourthLevel> fourthLevels = generalMapper.getLevelList(productsClassificationDTO).stream().map(FatherLevel::fromFourthLevel).toList();
                    //4.3装填四级分类数据
                    thirdLevel.setDataList(fourthLevels);
                }
                //3.3装填三级分类数据
                secondLevel.setDataList(thirdLevelArrayList);
            }
            //2.3装填二级分类数据
            firstLevel.setDataList(secondList);
        }
        //5. 返回数据
        return list;
    }

    private ArrayList<FirstLevel> getFirstList() {
        return generalMapper.getFirstList();
    }


    private FileInfo getFileInfo(FileInfo fileInfo) {
        FileInfo info = generalMapper.getFileInfo(fileInfo);
        return info;
    }


    private void setLevelNumber(ProductsClassificationDTO test) {
        //1. 准备工作
        Boolean flag = true;                                      //用于标记产品分类是否存在，存在则直接返回默认值true，不存在则是false
        //2. 需要获取判断产品分类ID是否存在，存在则直接返回levelID，不存在则是返回null
        Integer levelID = generalMapper.isLevelExist(test);
        //3. levelID为null,则需要获取最大值+1
        if (levelID == null) {
            try {
                levelID = generalMapper.mexLevel(test) + 1;
                flag = false;
            } catch (RuntimeException exception) {
                //3.1报错则代表也没有该值，直接设置为1
                switch (test.getLevelNumber()) {
                    case 1 -> test.setFirstClassificationId(LevelConstant.INIT_LEVEL);
                    case 2 -> test.setSecondClassificationId(LevelConstant.INIT_LEVEL);
                    case 3 -> test.setThirdClassificationId(LevelConstant.INIT_LEVEL);
                    case 4 -> test.setFourthLevelClassificationId(LevelConstant.INIT_LEVEL);
                    default ->
                            throw new RuntimeException(String.format(MessageConstant.DATA_ILLEGAL, LevelConstant.LEVEL_NUMBER));
                }
                return;
            }
        }
        //4.levelID存在，则需要填入ID，设置该分类存在
        switch (test.getLevelNumber()) {
            case 1 -> {
                test.setFirstClassificationId(levelID);
                test.setIsFirstExist(flag);
            }
            case 2 -> {
                test.setSecondClassificationId(levelID);
                test.setIsSecondExist(flag);
            }
            case 3 -> {
                test.setThirdClassificationId(levelID);
                test.setIsThirdExist(flag);
            }
            case 4 -> {
                test.setFourthLevelClassificationId(levelID);
                test.setIsFourthExist(flag);
            }
            default ->
                    throw new RuntimeException(String.format(MessageConstant.DATA_ILLEGAL, LevelConstant.LEVEL_NUMBER));
        }
    }

    private ArrayList<FileInfo> getFileArrayList(String[] split) {
        ArrayList<FileInfo> list = generalMapper.getFileArrayList(split);
        return list;
    }


    private FollowMethod getFollowMethod(FollowMethod followMethod) {
        return generalMapper.getFollowMethod(followMethod);
    }

    private CustomerDTO getCustomer(Integer id) {
        return generalMapper.getCustomer(id);
    }


    private Follow getFollow(Follow follow) {
        return generalMapper.getFollow(follow);
    }

    private Company getCompany(String companyName) {
        return generalMapper.getCompany(Company.builder().companyName(companyName).build());
    }

    private Company getCompany(Integer companyId) {
        return generalMapper.getCompany(Company.builder().companyId(companyId).build());
    }

    private Integer getDeptID(String deptName) {
        return generalMapper.getDeptID(deptName);
    }

    private Dept getDept(String deptName) {
        return getDept(Dept.builder().deptName(deptName).build());
    }

    private Dept getDept(Dept dept) {
        return generalMapper.getDept(dept);
    }

    private Integer getPostID(String postName) {
        return generalMapper.getPostID(postName);
    }

    private Employee getEmployee(Employee employee) {
        return generalMapper.getEmployee(employee);
    }

}
